<template>
  <div class="fill-height">
    <!-- 页面标题和导航 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <el-icon class="title-icon"><Setting /></el-icon>
          任务管理系统
        </h1>
      </div>
    </div>

    <!-- 导航按钮区域 -->
    <div class="navigation-section">
      <div class="nav-buttons">
        <el-button
          type="primary"
          class="nav-button"
          @click="$router.push('/dashboard')"
        >
          <el-icon><DataBoard /></el-icon>
          监控仪表盘
        </el-button>
        <el-button
          type="success"
          class="nav-button"
          @click="$router.push('/thread-pool-monitor')"
        >
          <el-icon><Monitor /></el-icon>
          线程池监控
        </el-button>
        <el-button
          type="warning"
          class="nav-button"
          @click="$router.push('/executor-runtime')"
        >
          <el-icon><Cpu /></el-icon>
          执行器运行情况
        </el-button>
        <el-button
          type="info"
          class="nav-button"
          @click="$router.push('/environment-monitor')"
        >
          <el-icon><DataAnalysis /></el-icon>
          环境监控
        </el-button>
      </div>
    </div>

    <!-- 任务触发器控制面板 -->
    <el-card class="trigger-control-card" shadow="hover">
      <div class="trigger-control-content">
        <div class="trigger-info">
          <el-icon class="trigger-icon"><Timer /></el-icon>
          <div class="trigger-text">
            <h3>任务触发器控制</h3>
            <p>控制定时任务触发处理器的开启和停止</p>
          </div>
        </div>
        <div class="trigger-actions">
          <div class="trigger-status">
            <span class="status-label">当前状态：</span>
            <el-tag 
              :type="triggerStatus === 'running' ? 'success' : 'danger'"
              size="large"
            >
              {{ triggerStatusData?.statusDescription || (triggerStatus === 'running' ? '运行中' : '已停止') }}
            </el-tag>
            <div v-if="triggerStatusData" class="status-details">
              <div class="status-detail-item">
                <span class="detail-label">启动时间：</span>
                <span class="detail-value">{{ triggerStatusData.startTime || '未知' }}</span>
              </div>
              <div class="status-detail-item">
                <span class="detail-label">最后更新：</span>
                <span class="detail-value">{{ triggerStatusData.lastUpdateTime || '未知' }}</span>
              </div>
            </div>
          </div>
          <el-space>
            <el-button
              type="success"
              size="large"
              :loading="triggerLoading"
              :disabled="triggerStatus === 'running'"
              @click="startTrigger"
            >
              <el-icon><VideoPlay /></el-icon>
              开启触发器
            </el-button>
            <el-button
              type="danger"
              size="large"
              :loading="triggerLoading"
              :disabled="triggerStatus === 'stopped'"
              @click="stopTrigger"
            >
              <el-icon><VideoPause /></el-icon>
              停止触发器
            </el-button>
            <el-button
              type="info"
              size="large"
              @click="loadTriggerStatus"
            >
              <el-icon><Refresh /></el-icon>
              刷新状态
            </el-button>
          </el-space>
        </div>
      </div>
    </el-card>

    <!-- 搜索条件和任务列表 -->
    <el-card class="main-content-card" shadow="hover">
      <!-- 搜索条件区域 -->
      <div class="search-section">
        <div class="search-header">
          <h3>搜索条件</h3>
        </div>
        <div class="search-form">
          <el-row :gutter="16">
            <el-col :span="6">
              <el-input
                v-model="searchForm.jobName"
                placeholder="模糊搜索任务名称/ClassName/描述/分片参数"
                clearable
              />
            </el-col>
            <el-col :span="4">
              <el-select
                v-model="searchForm.triggerStatus"
                placeholder="任务状态"
                clearable
                multiple
                collapse-tags
                collapse-tags-tooltip
              >
                <el-option
                  v-for="option in statusOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-input
                v-model="searchForm.groupName"
                placeholder="任务分组"
                clearable
              />
            </el-col>
            <el-col :span="6">
              <el-space>
                <el-button
                  type="primary"
                  @click="loadJobList"
                  :loading="loading"
                >
                  <el-icon><Search /></el-icon>
                  查询
                </el-button>
                <el-button @click="resetSearch">
                  <el-icon><Refresh /></el-icon>
                  清除
                </el-button>
              </el-space>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 任务列表区域 -->
      <div class="table-section">
        <div class="table-header">
          <div class="table-title">
            <h3>任务列表</h3>
          </div>
          <div class="table-actions">
            <el-button
              type="primary"
              @click="refreshList"
              :loading="loading"
            >
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>

      <el-table
        :data="jobList"
        :loading="loading"
        style="width: 100%"
        row-key="id"
        size="default"
      >
        <el-table-column prop="id" label="任务ID" width="80" />
        <el-table-column prop="jobName" label="任务名称" />
        <el-table-column prop="groupName" label="任务分组" />
        <el-table-column prop="jobDesc" label="任务描述" />
        <el-table-column prop="cronExpression" label="Cron表达式" />
        <el-table-column prop="scheduleType" label="调度类型">
          <template #default="{ row }">
            <el-tag type="info">
              {{ row.scheduleTypeDesc }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="triggerStatus" label="任务状态">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.triggerStatus)">
              {{ row.triggerStatusDesc }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="nextTriggerTime" label="下次触发时间" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-space>
              <el-button
                type="primary"
                size="small"
                @click="viewJobDetail(row)"
              >
                <el-icon><View /></el-icon>
                详情
              </el-button>
              <el-button
                type="success"
                size="small"
                @click="viewJobLogs(row)"
              >
                <el-icon><Document /></el-icon>
                日志
              </el-button>
              <el-button
                type="warning"
                size="small"
                @click="triggerJob(row)"
                :loading="triggeringJobs.get(row.id)"
              >
                <el-icon><VideoPlay /></el-icon>
                触发
              </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.pageNum"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {
  Setting,
  DataBoard,
  Monitor,
  Cpu,
  DataAnalysis,
  Timer,
  VideoPlay,
  VideoPause,
  Search,
  Refresh,
  View,
  Document
} from '@element-plus/icons-vue'
import {jobInfoApi, jobTriggerApi} from '@/services/api'
import type {JobInfoVO, JobInfoQueryDTO, ApiResult, PageResult, JobTriggerStatusVO} from '@/types/job'

const router = useRouter()
const fluid = ref<boolean>(false)
// 响应式数据
const loading = ref(false)
const jobList = ref<JobInfoVO[]>([])
const triggeringJobs = ref(new Map<number, boolean>())

// 任务触发器相关状态
const triggerStatus = ref<'running' | 'stopped'>('stopped')
const triggerLoading = ref(false)
const triggerStatusData = ref<JobTriggerStatusVO | null>(null)

// 搜索表单
const searchForm = reactive({
  jobName: '',
  triggerStatus: [] as number[],
  groupName: ''
})

// 分页信息
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 状态选项
const statusOptions = [
  {label: '停止', value: 0},
  {label: '运行中', value: 1}
]

// 获取状态类型
const getStatusType = (status: number) => {
  switch (status) {
    case 0:
      return 'danger'
    case 1:
      return 'success'
    default:
      return 'info'
  }
}

// 加载任务列表
const loadJobList = async () => {
  loading.value = true
  try {
    const params: JobInfoQueryDTO = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      triggerStatus: searchForm.triggerStatus.length > 0 ? searchForm.triggerStatus[0] : undefined,
      groupJobNames: searchForm.jobName ? [searchForm.jobName] : undefined
    }

    console.log(params)

    const response: ApiResult<PageResult<JobInfoVO>> = await jobInfoApi.queryJobInfoPage(params)
    console.log(response)
    if (response.code === 200) {
      jobList.value = response.data.records
      console.log('任务列表加载成功', jobList.value)
      pagination.total = response.data.total
    } else {
      console.error('加载任务列表失败:', response.message)
    }
  } catch (error) {
    console.error('加载任务列表出错:', error)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.jobName = ''
  searchForm.triggerStatus = []
  searchForm.groupName = ''
  pagination.pageNum = 1
  loadJobList()
}

// 刷新列表
const refreshList = () => {
  loadJobList()
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  loadJobList()
}

// 处理当前页变化
const handleCurrentChange = (page: number) => {
  pagination.pageNum = page
  loadJobList()
}

// 查看任务详情
const viewJobDetail = (job: JobInfoVO) => {
  router.push(`/job-detail/${job.id}`)
}

// 查看任务日志
const viewJobLogs = (job: JobInfoVO) => {
  router.push(`/job-logs/${job.id}`)
}

// 触发任务
const triggerJob = async (job: JobInfoVO) => {
  triggeringJobs.value.set(job.id, true)

  try {
    const response: ApiResult<string> = await jobInfoApi.triggerJob(job.id)
    if (response.success) {
      // 显示成功消息
      console.log('任务触发成功')
      // 刷新列表
      loadJobList()
    } else {
      console.error('任务触发失败:', response.message)
    }
  } catch (error) {
    console.error('触发任务出错:', error)
  } finally {
    triggeringJobs.value.set(job.id, false)
  }
}

// 开启任务触发器
const startTrigger = async () => {
  try {
    triggerLoading.value = true
    const result = await jobTriggerApi.startJobTrigger()
    if (result.success) {
      ElMessage.success('任务触发器已开启')
      triggerStatus.value = 'running'
      // 重新获取状态
      await loadTriggerStatus()
    } else {
      ElMessage.error(result.message || '开启失败')
    }
  } catch (error) {
    console.error('开启任务触发器失败:', error)
    ElMessage.error('开启任务触发器失败')
  } finally {
    triggerLoading.value = false
  }
}

// 停止任务触发器
const stopTrigger = async () => {
  try {
    triggerLoading.value = true
    const result = await jobTriggerApi.stopJobTrigger()
    if (result.success) {
      ElMessage.success('任务触发器已停止')
      triggerStatus.value = 'stopped'
      // 重新获取状态
      await loadTriggerStatus()
    } else {
      ElMessage.error(result.message || '停止失败')
    }
  } catch (error) {
    console.error('停止任务触发器失败:', error)
    ElMessage.error('停止任务触发器失败')
  } finally {
    triggerLoading.value = false
  }
}

// 获取任务触发器状态
const loadTriggerStatus = async () => {
  try {
    const response: ApiResult<JobTriggerStatusVO> = await jobTriggerApi.getJobTriggerStatus()
    if (response.success) {
      triggerStatusData.value = response.data
      triggerStatus.value = response.data.running ? 'running' : 'stopped'
    } else {
      console.error('获取触发器状态失败:', response.message)
    }
  } catch (error) {
    console.error('获取触发器状态出错:', error)
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadJobList()
  loadTriggerStatus()
})
</script>

<style scoped>
.page-header {
  margin-bottom: 16px;
}

.header-content {
  display: flex;
  justify-content: center;
  align-items: center;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  display: flex;
  align-items: center;
}

.title-icon {
  margin-right: 12px;
  color: #409eff;
  font-size: 28px;
}

.navigation-section {
  margin-bottom: 24px;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.nav-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
  flex-wrap: wrap;
}

.nav-button {
  min-width: 140px;
  height: 48px;
  font-size: 14px;
  font-weight: 600;
  border-radius: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.nav-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.trigger-control-card {
  margin-bottom: 24px;
  border: 2px solid #e0e0e0;
  border-radius: 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.trigger-control-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}

.trigger-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.trigger-icon {
  font-size: 32px;
  color: #409eff;
}

.trigger-text h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.trigger-text p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.trigger-actions {
  display: flex;
  align-items: center;
  gap: 24px;
}

.trigger-status {
  display: flex;
  align-items: center;
  gap: 12px;
}

.status-label {
  font-size: 16px;
  color: #606266;
  font-weight: 500;
}

.status-details {
  margin-top: 8px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.status-detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
  font-size: 12px;
}

.status-detail-item:last-child {
  margin-bottom: 0;
}

.detail-label {
  color: #606266;
  font-weight: 500;
  min-width: 80px;
}

.detail-value {
  color: #303133;
  font-weight: 600;
}

.main-content-card {
  margin-bottom: 24px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.search-section {
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
  background: #f8f9fa;
}

.search-header h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.search-form {
  margin-top: 16px;
}

.table-section {
  padding: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-title h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.table-actions {
  display: flex;
  gap: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.fill-height {
  width: 80vw;
  max-width: 1200px;
  margin: 0 auto;
}

/* 现代化表格样式 */
.el-table {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
}

/* 表格右上角45度切角标签 */

/* 表头样式 */
.el-table :deep(.el-table__header-wrapper) {
  background: #f1f5f9;
}

.el-table :deep(.el-table__header) {
  background: #f1f5f9;
}

.el-table :deep(.el-table__header th) {
  background: #f1f5f9 !important;
  color: #475569;
  font-weight: 600;
  font-size: 14px;
  padding: 16px 12px;
  border-bottom: 2px solid #cbd5e1;
  border-right: 1px solid #cbd5e1;
  text-align: left;
  position: relative;
}

.el-table :deep(.el-table__header th:last-child) {
  border-right: none;
}

/* 表格内容样式 */
.el-table :deep(.el-table__body-wrapper) {
  background: #ffffff;
}

.el-table :deep(.el-table__body tr) {
  background: #ffffff;
  transition: background-color 0.2s ease;
}

/* 隔行换色 */
.el-table :deep(.el-table__body tr:nth-child(even)) {
  background: #f8f9fa;
}

.el-table :deep(.el-table__body tr:hover) {
  background: #e3f2fd !important;
}

/* 单元格样式 */
.el-table :deep(.el-table__body td) {
  padding: 16px 12px;
  border-bottom: 1px solid #e0e0e0;
  border-right: 1px solid #e0e0e0;
  font-size: 14px;
  color: #2c3e50;
  text-align: left;
  position: relative;
}

.el-table :deep(.el-table__body td:last-child) {
  border-right: none;
}

/* 数字列右对齐 */
.el-table :deep(.el-table__body td[data-numeric="true"]) {
  text-align: right;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-weight: 500;
}

/* 状态标签样式 */
.el-table :deep(.el-tag) {
  border-radius: 0;
  font-weight: 600;
  padding: 4px 8px;
  border: 1px solid;
  position: relative;
}

.el-table :deep(.el-tag--success) {
  background: #e8f5e8;
  border-color: #4caf50;
  color: #2e7d32;
}

.el-table :deep(.el-tag--warning) {
  background: #fff8e1;
  border-color: #ff9800;
  color: #f57c00;
}

.el-table :deep(.el-tag--danger) {
  background: #ffebee;
  border-color: #f44336;
  color: #c62828;
}

.el-table :deep(.el-tag--info) {
  background: #e3f2fd;
  border-color: #2196f3;
  color: #1565c0;
}



/* 关键数据标注 */
.el-table :deep(.el-table__body td[data-key="true"]) {
  position: relative;
}

.el-table :deep(.el-table__body td[data-key="true"]::before) {
  content: '◆';
  position: absolute;
  left: 4px;
  top: 50%;
  transform: translateY(-50%);
  color: #409eff;
  font-size: 12px;
  font-weight: bold;
}

/* 卡片样式优化 */
.el-card {
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.el-card :deep(.el-card__header) {
  background: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
  padding: 16px 20px;
}

.el-card :deep(.el-card__body) {
  padding: 20px;
}

/* 按钮样式优化 */
.el-button {
  border-radius: 6px;
  font-weight: 600;
  border: 1px solid;
  transition: all 0.3s ease;
}

.el-button--primary {
  background: #409eff;
  border-color: #409eff;
}

.el-button--primary:hover {
  background: #337ecc;
  border-color: #337ecc;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

.el-button--success {
  background: #67c23a;
  border-color: #67c23a;
}

.el-button--success:hover {
  background: #5daf34;
  border-color: #5daf34;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(103, 194, 58, 0.3);
}

.el-button--warning {
  background: #e6a23c;
  border-color: #e6a23c;
}

.el-button--warning:hover {
  background: #cf9236;
  border-color: #cf9236;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(230, 162, 60, 0.3);
}

/* 输入框和选择器样式优化 */
.el-input :deep(.el-input__wrapper),
.el-select :deep(.el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid #e0e0e0;
  box-shadow: none;
  transition: all 0.3s ease;
}

.el-input :deep(.el-input__wrapper:hover),
.el-select :deep(.el-input__wrapper:hover) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.el-input :deep(.el-input__wrapper.is-focus),
.el-select :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 分页样式优化 */
.el-pagination {
  margin-top: 20px;
  text-align: right;
}

.el-pagination :deep(.el-pager li) {
  border-radius: 4px;
  border: 1px solid #e0e0e0;
  margin: 0 2px;
  transition: all 0.3s ease;
}

.el-pagination :deep(.el-pager li:hover) {
  border-color: #409eff;
  color: #409eff;
}

.el-pagination :deep(.el-pager li.is-active) {
  background: #409eff;
  border-color: #409eff;
  color: #ffffff;
}

/* 搜索表单样式优化 */
.search-form :deep(.el-form-item__label) {
  font-weight: 600;
  color: #2c3e50;
}
</style>
